package com.lm.eureka.listener;

import com.netflix.appinfo.InstanceInfo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.netflix.eureka.server.event.*;
import org.springframework.context.event.EventListener;

/**
 * Eureka事件监听
 *
 * @author lm
 * @date 2019/4/3 14:44
 */
//@Component
public class EurekaStateListener {

    private final static Logger logger = LoggerFactory.getLogger(EurekaStateListener.class);

    @EventListener
    public void listen(EurekaRegistryAvailableEvent event) {
        logger.info("注册中心启动,{},{}", System.currentTimeMillis(), event);
    }

    @EventListener
    public void listen(EurekaServerStartedEvent event) {
        logger.info("注册中心服务端启动,{},{}", System.currentTimeMillis(), event);
    }

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceRegisteredEvent event) {
        InstanceInfo instanceInfo = event.getInstanceInfo();
        logger.info("服务{}进行注册,{},{},{}", instanceInfo.getAppName(), instanceInfo.getHostName(), instanceInfo.getIPAddr(), instanceInfo.getPort());
    }

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceRenewedEvent event) {
        logger.info("服务{}进行续约,{}", event.getServerId(), event.getAppName());
    }

    @EventListener//(condition = "#event.replication==false")
    public void listen(EurekaInstanceCanceledEvent event) {
        logger.info("服务{}已下线, SERVER地址信息{}", event.getAppName(), event.getServerId());

//        EurekaInstanceCanceledEvent event = (EurekaInstanceCanceledEvent) applicationEvent;
//        // 获取当前Eureka实例中的节点信息
//        PeerAwareInstanceRegistry registry = EurekaServerContextHolder.getInstance().getServerContext().getRegistry();
//        Applications applications = registry.getApplications();
//        // 遍历获取已注册节点中与当前失效节点ID一致的节点信息
//        applications.getRegisteredApplications().forEach((registeredApplication) -> {
//            registeredApplication.getInstances().forEach((instance) -> {
//                if (instance.getInstanceId().equals(event.getServerId())) {
//                    logger.debug("服务：" + instance.getAppName() + " 挂啦。。。");
//                    // TODO: 扩展消息提醒 邮件、手机短信、微信等
//                }
//            });
//        });
    }

}